package public

import (
	"com.cyt.common/library/encrypt"
	"github.com/gogf/gf/crypto/gmd5"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"github.com/gogf/gf/net/ghttp"
	"time"
)

// 公共网关请求
type GatewayClient struct {
	Client *ghttp.Client
}

type Param struct {
	Time     int    `json:"time"`
	Salt     string `json:"salt"`
	Token    string `json:"token"`
	AppUid   string `json:"token"`
	ClientId string `json:"clientId"`
}

func NewClient(params ...string) *GatewayClient {
	c := &GatewayClient{}
	GatewayUrl := g.Cfg().GetString("cyt_gateway.common.gateway_url", "http://129.204.71.240")
	SATL := g.Cfg().GetString("cyt_gateway.common.satl", "giao")
	ClientId := g.Cfg().GetString("cyt_gateway.common.client_id", "xcqgivykve45sexy6vhopu6gieridrnw")
	Secret := g.Cfg().GetString("cyt_gateway.common.secret", "jl8ax3171kkeyo4nmvzvde2ek36g7d08zytg25h6")
	var appUid string
	if len(params) > 0 {
		appUid = params[0]
	}

	currentTime := gconv.Int(time.Now().Unix())
	first, _ := gmd5.Encrypt(SATL + gconv.String(currentTime) + appUid + ClientId + Secret + SATL)
	token, _ := gmd5.Encrypt(first)
	param := g.Map{
		"time":     currentTime,
		"salt":     SATL,
		"token":    token,
		"appUid":   appUid,
		"clientId": ClientId,
	}

	sign, err := encrypt.LaravelEncrypt("", gconv.String(param), false)
	if err != nil {
		panic(err)
	}

	c.Client = g.Client().SetPrefix(GatewayUrl).SetHeader("G-Sign-V1", sign).SetTimeout(60 * time.Second)
	return c
}

// 采集拼多多详情
func (c *GatewayClient) GetPddGoodsInfo(goodsId string) (string, error) {
	response := c.Client.SetRetry(5, 5 * time.Second).GetContent("/ycj/api/pdd/goodsDetailWeb", g.Map{"goodsId": goodsId, "ycr": 1, "cacheCycle": 0.1})
	return response, nil
}
